package cn.tedu.csmall.passport;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@SpringBootTest
public class JWT {
    @Value("${csmall.jwt.secret-key}")
    String secretKey;//秘钥错误会报出SignatureException异常
    @Test
    void genereat(){
        //https://jwt.io/introduction
        String secretkey="dsfdsfsdgshhrwnhb";//保密字符  秘钥
        /*手机端一般保留一个月*/
        Date date=new Date(System.currentTimeMillis()+2*60*1000);//两分钟后过期  过期后再进行会报出ExpiredJwtException异常
        Map<String,Object> claims=new HashMap<>();
        claims.put("id",123);
        claims.put("username","zhangsan");
        //创建JWT构建器builder
        String jwt= Jwts.builder()
                .setHeaderParam("alg","HS256").setHeaderParam("typ","JWT")
                .setClaims(claims)
                .setExpiration(date)
                .signWith(SignatureAlgorithm.HS256,secretkey)
                .compact();
        log.debug(jwt);
    }
    @Test
    void parse(){
        String jwt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzLCJleHAiOjE2Njc4NzkzNDgsInVzZXJuYW1lIjoiemhhbmdzYW4ifQ.Y-omczJelDkIl582yUxTaMeCPxuSld6stbZmPWS2uWE";
        //创建JWT解析器parser
        Claims claims=Jwts.parser()
                .setSigningKey(secretKey)
                .parseClaimsJws(jwt)
                .getBody();
        Object id=claims.get("id",Long.class);//long.class指定数据类型
        Object username=claims.get("username",String.class);

        log.debug("{},{}",id,username);
    }
}
